var db;
var menuOpen = false;
var menuDiv = "";
var theme;

function onDeviceReady() {
	menuDiv = document.querySelector(".menu");

	theme = window.localStorage.getItem("theme");
	$('.jqm-page').trigger('refresh', theme);

	document.addEventListener("menubutton", onMenuKeyDown, false);
	try {
		var DbName = "RssList_DB";
		var version = "1.0";
		var displayName = "A RssList Database";
		var maxSize = 200000;
		db = window.openDatabase(DbName, version, displayName, maxSize);
	} catch (e) {
		console.log(e);
	}
	db.transaction(populateDB, errorCB, successCB);
}
// 创建数据表RssList
function populateDB(tx) {
	tx.executeSql('CREATE TABLE IF NOT EXISTS RssList (id INTEGER PRIMARY KEY AUTOINCREMENT,Name,Link,Flag)');
}
// 事务执行出错后调用的回调函数
function errorCB(err) {
	console.log("Error processing SQL: " + err.code);
}
// 事务执行成功后调用的回调函数 查询数据
function successCB() {
	db.transaction(function(tx) {
		tx.executeSql("SELECT * FROM RssList", [], querySuccess, errorCB);
	}, errorCB);
}

function querySuccess(tx, result) {
	if (result.rows.length == 0) {
		$("#tipsContent").text("没有订阅RSS新闻").show();
		$("#mainContent").hide();
		/* $("#RssListView").hide(); */
	} else {
		$("#tipsContent").hide();
		$("#mainContent").show();
		/* $("#RssListView").show(); */
		var list = $('#RssListView');
		$('#RssListView').empty();
		$.each(result.rows, function(index) {
			var row = result.rows.item(index);
			// console.log(row['id']);
			$('#RssListView').append(
					'<li data-icon="false"><a id="rssNewsA" href="javascript:void(0)" my-data="' + row['Name'] + '#' + row['Link'] + '">'
							+ row['Name'] + '</a><span  class="ui-li-count">' + row['Flag'] + '</span><a id="deleteRssNews" "my-id=' + row['id']
							+ ' data-inline="true"  data-rel="dialog" data-transition="slideup"></a></li>');
		});
		list.listview('refresh');

	}
}

// 向数据表中插入订阅的Rss
function insertRss(Rss, cb) {
	// alert(" 标题:" + Rss.name + "地址:" + Rss.link + "标签:" + Rss.flag)
	// Sometimes you may want to jot down something quickly....
	db.transaction(function(tx) {
		tx.executeSql("insert into RssList(Name,Link,Flag) values(?,?,?)", [ Rss.name, Rss.link, Rss.flag ]);
	}, errorCB, cb);

}
// 删除订阅的RSS
function deleteRss(id, cb) {
	// Sometimes you may want to jot down something quickly....
	// alert("id=" + id);
	db.transaction(function(tx) {
		tx.executeSql("DELETE FROM RssList where id=?", [ id ]);
	}, errorCB, cb);
}

// 首页面初始化
function init() {
	document.addEventListener("deviceready", onDeviceReady, false);
	$("#index").live("pageshow", function() {
		closeMenu();
		successCB();
	});
}

function closeMenu() {
	$(".menu").attr("style", "display: none;");
	menuOpen = false;
}

/* 根据url地址解析RSS内容 */
function parseFeed(url) {
	$.getFeed({
		url : url,
		dataType : "xml",
		success : function(feed) {
			var list = $('#newsListPageListView');
			$('#newsListPageListView').empty();
			if (feed.items.length == 0) {
				$("#newsListPageContent").html("<p>没有订阅RSS新闻</p>");
				$('#newsListPageListView').hide();
			} else {
				for ( var i = 0; i < feed.items.length; i++) {
					var item = feed.items[i];
					// console.log(item.updated);
					$('#newsListPageListView').append(
							'<li data-icon="false" ><a href="javascript:void(0)" my-data="' + item.title + '#' + item.link + '#' + item.updated + '#'
									+ item.description + '">' + item.title + '</a></li>');
				}
				list.listview('refresh');
				window.plugins.PGLoadingDialog.hide();
			}
		}
	});
}

/*
 * 网络检测函数
 */
function checkConnection() {
	var networkState = navigator.network.connection.type;
	var states = {};
	states[Connection.UNKNOWN] = 'Unknown connection';
	states[Connection.ETHERNET] = 'Ethernet connection';
	states[Connection.WIFI] = 'WiFi connection';
	states[Connection.CELL_2G] = 'Cell 2G connection';
	states[Connection.CELL_3G] = 'Cell 3G connection';
	states[Connection.CELL_4G] = 'Cell 4G connection';
	states[Connection.NONE] = 'No network connection';
	//alert("Connection type:" + states[networkState]);
	if (states[networkState] == 'No network connection')
		return false;
	return true;
}
/* 网页跳转函数 */
function MyChangePage(page, args) {
	$.mobile.changePage(page, {
		transition : "none"
	});

	$(page).trigger("callback", args);
}

// 点击菜单按钮15:33
function onMenuKeyDown() {
	if (menuOpen) {
		// console.log("close the menu");
		menuDiv.style.display = "none";
		menuOpen = false;
	} else {
		// console.log("open the menu");
		menuDiv.style.display = "block";
		menuOpen = true;
	}
}
// 退出应用程序
function exitApp() {
	try {
		navigator.notification.confirm('你确定要退出应用程序?', doExit, '信息提示!', '取消,退出');
		function doExit(button) {
			if (button == 2) {
				navigator.app.exitApp();
			} else if (button == 1) { // do nothing
				menuDiv.style.display = "none";
				menuOpen = false;
			}
		}
	} // try end
	catch (err) {
		alert('ExitApp failed' + err)
	} // catch end
}
// 提示信息函数
function showAlert(msg) {
	navigator.notification.alert(msg, // 信息
	alertDismissed, '信息提示！', // 标题
	'关闭');

}
function alertDismissed() {
	// do something
}
